<?php

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Db;
use \api\zmt\model\WalletModel;
//公共函数文件

//生成TOKEN
function signToken($id,$mobile)
{
    $data = [
        //签发人
        'iss' => request()->domain(),
        //签发时间
        'iat' => time(),
        //到期时间，1天后
        //'exp' =>time() + 86400,
        //自定义数据
        'data' => [
            'id' => $id,
            'mobile' => $mobile,
        ]
    ];
    $key = config('app.jwt_key');
    $token = \Firebase\JWT\JWT::encode($data,$key,'HS256');
    return $token;
}

//验证码
function sendAliSms($mobile)
{
    $code = mt_rand(1111,9999);

    $config = new Config([
        // 从阿里云获取
        'accessKeyId' => config('app.aliSms.accessKeyId'),
        'accessKeySecret' => config('app.aliSms.accessKeySecret'),
    ]);

    $config->endpoint = "dysmsapi.aliyuncs.com";
    $client = new Dysmsapi($config);

    // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
    $runtimeOptions = new RuntimeOptions();
    // true 忽略证书校验
    $runtimeOptions->ignoreSSL = true;

    $sendSmsRequest = new SendSmsRequest();
    // 手机号
    $sendSmsRequest->phoneNumbers = $mobile;
    // 签名名称
    $sendSmsRequest->signName = '阿里云短信测试';
    // 模板CODE
    $sendSmsRequest->templateCode = 'SMS_154950909';
    // 生成随机数作为验证码
    $sendSmsRequest->templateParam = json_encode(['code' => $code]);
    try {
        $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
    } catch (\Exception $exception) {
        halt($exception->getMessage());
    }
    if ($response->body->code == 'OK') {
        Db::name('sms_code_log')->insert([
            'code' => $code,
            'mobile' => $mobile,
            'send_time' => time()
        ]);
        return ['code' => 1,'msg' => '短信发送成功'];//'短信发送成功！';
    }else{
        return ['code' => 0,'msg' => $response->body->message];
    }
}

function checkSmsCode($mobile,$code){
    $log = \think\facade\Db::name('sms_code_log')
        ->where('mobile',$mobile)
        ->find();
    if(!$log) {
        return false;
    }
    if($log['code'] != $code) {
        return false;
    }
    if(time() - $log['send_time'] > 60) {
        //删除
        Db::name('sms_code_log')->where('mobile',$mobile)->delete();
        return false;
    }
    //删除
    Db::name('sms_code_log')->where('mobile',$mobile)->delete();
    return true;
}

//上传
function upload(){
    class Test
    {
        private $accessKey = "9qaHuH1vYSvNv-u5fDnYpASluywSrp5PeeFJnm6O"; // 你的 AccessKey
        private $secretKey = "veE0IP96vf4csV7_Cf1Tg4MKd1_xWkeo_a--PKyX"; // 你的 SecretKey
        private $bucket = "thinkphp-demo"; // 你在七牛云创建的空间名称

        // 图片上传七牛云
        public function uploadToQiniu()
        {
            if (request()->isPost()) {
                $file = request()->file('file');
                //原文件名
                $oldFileName = $file->getOriginalName();
                //截取后缀名
                $ext = strrchr($oldFileName,'.');
                //重命名
                $newName = time().mt_rand(111,999).$ext;
                //初始化签权对象
                $auth = new Auth(config('qiniu.ak'),config('qiniu.sk'));
                // 生成上传 Token
                $token = $auth->uploadToken(config('qiniu.bucket'));
                //构建 UploadManager 对象
                $uploadMgr = new UploadManager();
                // 调用 UploadManager 的 putFile 方法进行文件的上传。
                list($ret, $err) = $uploadMgr->putFile($token, $newName, $file->getPathname(), null, 'application/octet-stream', true, null, 'v2');
                if ($err !== null) {
                    //var_dump((array)$err['Qiniu\Http\Errorresponse']);
                    var_dump($err);
                } else {
                    return json(['code' => 1,'msg' => '上传成功','data'=>[
                        'url' => 'http://s2pbc53k3.hb-bkt.clouddn.com/'.$ret['key']
                    ]]);
                    //var_dump($ret);
                }
            }
            return view();
        }
    }
}
//充值余额
function money_log($user_id,$wallet,$before,$after,$type)
{
    $money_log = [
        'user_id' => $user_id,
        'money' => $wallet,
        'before' => $before,
        'after' => $after,
        'type' => $type,
        'create_time' => date('Y:m:d H:i:s')
    ];
    $res = WalletModel::create($money_log);
    if ($res) {
        return json(['code' => '1', 'msg' => '流水记录添加成功']);
    } else {
        return json(['code' => '0', 'msg' => '流水记录添加失败']);
    }
}

